import pygame
import time

from calendar import Calendar, lucun, kui_yue, yangren, wenchang, jiesha, yima, taohua, jiangxing, huagai, mouxing, tianyi
from sixty_four_guas import get_gua_data, get_liuqin, get_yao_dizhi, get_liushen

GREY = (192, 192, 192)
BLACK = (0, 0, 0)

WIDTH = 800
HEIGHT = 600

YANG_LENGTH = 130
YIN_LENGTH = 55
YAO_HEIGHT = 20

GUA_X_PADDING = 170
GUA_Y_PADDING = 330

CELL_WIDTH = 150

STAIC_GUA_PADDING = (WIDTH - YANG_LENGTH) // 2

DATE_X_PADDING = 80
DATE_Y_PADDING = 30

LIUSHEN_X_PADDING = 20
FUSHEN_X_PADDING = 100

pygame.init()
screen = pygame.display.set_mode((800, 600))

screen.fill(GREY)


class GuaPlate(object):
    def __init__(self, ben_yaos, zhi_yaos, month, day) -> None:
        self.month = month
        self.day = day

        if ben_yaos == zhi_yaos:
            self.ben_gua = Gua(ben_yaos, STAIC_GUA_PADDING, GUA_Y_PADDING, -1)
            self.zhi_gua = None
        else:
            self.ben_gua = Gua(ben_yaos, GUA_X_PADDING, GUA_Y_PADDING, -1)
            self.zhi_gua = Gua(zhi_yaos, WIDTH - GUA_X_PADDING - YANG_LENGTH, GUA_Y_PADDING, self.ben_gua.zhugua_guagong)

        self.ben_gua.make_bianyao(self.zhi_gua)
        self.ben_gua.make_fushen()

    def draw(self, screen):
        self.draw_month_day(screen)
        self.draw_shensha(screen)

        if (self.ben_gua):
            self.ben_gua.make_liushen(self.day)
            self.ben_gua.draw(screen)
        if (self.zhi_gua):
            self.zhi_gua.draw(screen)

    def draw_shensha(self, screen):
        data = []
        data.append(("贵人：%s", kui_yue.get(self.day[0])))
        data.append(("禄存：%s", lucun.get(self.day[0])))
        data.append(("羊刃：%s", yangren.get(self.day[0])))
        data.append(("文昌：%s", wenchang.get(self.day[0])))
        data.append(("驿马：%s", yima.get(self.day[1])))
        data.append(("桃花：%s", taohua.get(self.day[1])))
        data.append(("将星：%s", jiangxing.get(self.day[1])))
        data.append(("劫煞：%s", jiesha.get(self.day[1])))
        data.append(("华盖：%s", huagai.get(self.day[1])))
        data.append(("谋星：%s", mouxing.get(self.day[1])))
        data.append(("天医：%s", tianyi.get(self.month)))
        data.append(("天喜：%s", ""))
        data.append(("胎爻：%s", ""))
        data.append(("灾煞：%s", ""))
        data.append(("床帐：%s", ""))
        data.append(("卦身：%s", ""))

        index = 0
        for k, v in data:
            text = yahei_font.render(k % v, True, BLACK)
            line = index // 4 + 1
            row  = index % 4
            screen.blit(text, (DATE_X_PADDING + row * CELL_WIDTH, DATE_Y_PADDING + YAO_HEIGHT * 2 * line))
            index += 1
            

    def draw_month_day(self, screen):
        text = yahei_font.render("%s月 %s日（旬空：%s）" % (self.month, self.day, Calendar.calc_xunkong(self.day)), True, BLACK)
        screen.blit(text, (DATE_X_PADDING, DATE_Y_PADDING))


class Gua(object):
    def __init__(self, name, x, y, zhuguagong) -> None:
        # ["乾", ("111111", "乾为天", 5)]
        gua_data = get_gua_data(name)
        yaos = gua_data[1][0]
        
        if (len(yaos) != 6):
            print("Error : Gua only have 6 yaos.")

        self.yaos = yaos
        self.guagong = gua_data[0]
        self.label = gua_data[1][1]
        self.shiyao = 5 - gua_data[1][2]
        self.yingyao = (self.shiyao + 3) % 6
        self.x = x
        self.y = y
        self.zhugua_guagong = self.guagong if zhuguagong == -1 else zhuguagong

        self.dizhi_labels = get_yao_dizhi(self.yaos)
        self.liuqin = get_liuqin(self.zhugua_guagong, self.dizhi_labels)
        self.liushen_labels = None
        self.bian_labels = None
        self.fushen = None

    def make_bianyao(self, zhigua):
        if (zhigua is None):
            return
        
        zhi_yaos = zhigua.yaos
        bian_labels = []

        for i in range(6):
            if (self.yaos[i] != zhi_yaos[i]):
                if self.yaos[i] == '0':
                    bian_labels.append("X-->")
                else:
                    bian_labels.append("O-->")
            else:
                bian_labels.append("")

        self.bian_labels = bian_labels

    def make_fushen(self):
        primay = Gua(self.guagong, 0, 0, -1)
        fushen = []

        for i in range(6):
            if primay.liuqin[i] not in self.liuqin:
                fushen.append(primay.liuqin[i] + Calendar.DIZHI[primay.dizhi_labels[i] - 1])
            else:
                fushen.append("")
        
        self.fushen = fushen

    def make_liushen(self, day):
        self.liushen_labels = get_liushen(day[0])

    def draw(self, screen):
        text = yahei_font.render("%s宫：%s" % (self.guagong, self.label), True, BLACK)
        screen.blit(text, (self.x, self.y - YAO_HEIGHT * 2))

        i = 0
        for e in self.yaos:
            self.draw_yao(screen, e, i)
            i += 1

    def draw_yao(self, screen, yao, index):
        if (yao == "1"):
            pygame.draw.rect(screen, BLACK, (self.x, self.y + YAO_HEIGHT * 2 * index, YANG_LENGTH, YAO_HEIGHT))
            
        else:
            pygame.draw.rect(screen, BLACK, (self.x, self.y + YAO_HEIGHT * 2 * index, YIN_LENGTH, YAO_HEIGHT))
            pygame.draw.rect(screen, BLACK, (self.x + YANG_LENGTH - YIN_LENGTH, self.y + YAO_HEIGHT * 2 * index, YIN_LENGTH, YAO_HEIGHT))

        shiying = "  "
        if index == self.shiyao:
            shiying = "世"
        elif index == self.yingyao:
            shiying = "应"

        jiaochong = ""
        if self.bian_labels:
            jiaochong = self.bian_labels[index]

        label = "%s%s %s %s %s" % ("", Calendar.DIZHI[self.dizhi_labels[index] - 1], 
                                   self.liuqin[index], 
                                   shiying,
                                   jiaochong)

        text = kai_font.render(label, True, BLACK)
        screen.blit(text, (self.x + YANG_LENGTH + 20, self.y + YAO_HEIGHT * 2 * index))

        # 装伏神
        if self.fushen:
            text = fangsong_font.render(self.fushen[index], True, BLACK)
            screen.blit(text, (FUSHEN_X_PADDING, self.y + YAO_HEIGHT * 2 * index))
        
        # 画六神
        if self.liushen_labels:
            text = kai_font.render(self.liushen_labels[index], True, BLACK)
            screen.blit(text, (LIUSHEN_X_PADDING, self.y + YAO_HEIGHT * 2 * index))
        

name = pygame.font.match_font("kaiti")
kai_font = pygame.font.Font(name, YAO_HEIGHT)
fangsong_font = pygame.font.SysFont("FangSong", YAO_HEIGHT)
yahei_font = pygame.font.SysFont("Microsoft YaHei", YAO_HEIGHT)


def draw_all(screen):
    plate = GuaPlate("观", "涣", "辰", "戊申")
    plate.draw(screen)

draw_all(screen)
pygame.display.update()

going = True
while going:
    for evt in pygame.event.get():
        if evt.type == pygame.QUIT:
            going = False

    time.sleep(0.2)
